package com.xiongjie.SingleCache.service;

import com.xiongjie.SingleCache.Interface.impl.ISingleCacheImpl;
import com.xiongjie.SingleCache.entity.SingleCacheEntity;
import org.infinispan.Cache;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SSingleCacheService extends ISingleCacheImpl {

   final private static String BASE_URL = "http://.../...";
   private DocumentBuilder db;
   private final String apiKey;

   public SSingleCacheService(String apiKey, Cache<String, SingleCacheEntity> cache) {
      super(cache);
      this.apiKey = apiKey;
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      try {
         db = dbf.newDocumentBuilder();
      } catch (ParserConfigurationException e) {
      }
   }

   @Override
   protected SingleCacheEntity getSingleCacheEntity(String name) {

      Document dom = getData(name);
      //多个element元素，获取想要的数据
      Element current = (Element) dom.getElementsByTagName("...").item(0);

      //TODO 中间的操作

      return new SingleCacheEntity(current.getAttribute("value"), name.trim());
   }

   /**
    * 解析http请求返回的xml数据
    * @param name
    * @return
    */
   private Document getData(String name) {
      HttpURLConnection conn = null;
      try {
         String query = String.format("%s?...%s...%s...", BASE_URL,
                 URLEncoder.encode(name.replaceAll(" ", ""), "UTF-8"), apiKey);

         //发送请求
         URL url = new URL(query);
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Accept", "application/xml");

         //TODO 中间的操作

         if (conn.getResponseCode() != 200) {
            throw new Exception();
         }
         return db.parse(conn.getInputStream());
      } catch (Exception e) {
         return null;
      } finally {
         if (conn != null) {
            conn.disconnect();
         }
      }
   }

}
